import CryptoJS                          from 'crypto-js';
import md5                               from 'js-md5'

let platform = 'pc';
let device   = '';
let lang     = '';
let uid      = '';
let token    = '';
let appid    = '';
let version = process.env.VERSION;

self.addEventListener('message',ev => {
    let res = ev.data;
    if(res.action === 'baseInfo'){
        if(res.value.lang) lang = res.value.lang;
        if(res.value.device) device = res.value.device;
        if(res.value.appid) appid = res.value.appid;
        if(res.value.token) token = res.value.token;
        if(res.value.uid) uid = res.value.uid;
    }
});

//获取随机字符串 e 字符串长度
function randomString (e) {
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
        a = t.length,
        n = "";
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
}

//对象asscii 排序
function sort_ASCII (obj) {
    var arr = new Array();
    var num = 0;
    for (var i in obj) {
        arr[num] = i;
        num++;
    }
    var sortArr = arr.sort();
    var sortObj = {};
    for (var i in sortArr) {
        sortObj[sortArr[i]] = obj[sortArr[i]];
    }
    return sortObj;
}

//对象转URL参数
function objTransUrlParams (obj) {
    const params = [];
    Object.keys(obj).forEach(key => {
        let value = obj[key];
        if (typeof value === 'undefined') {
            value = ''
        }
        params.push(key+'='+value)
    })
    return params.join('&')
}

//获取签名信息
export function getHashStr (strObj = {}) {
    let appKey = {
        appid: 547798,
        appsecret: '61dd6c49529a05569900e71f49a0cd87',
    }
    strObj['appid'] = appKey.appid
    strObj['randomstr'] = randomString(6)
    strObj['timestamp'] = new Date().getTime();
    strObj['convertPOST'] = 1;
    strObj = sort_ASCII(strObj)
    let queryStr = objTransUrlParams(strObj)
    let hash = CryptoJS.HmacSHA256(queryStr, appKey.appsecret).toString();
    return md5(hash).toLocaleLowerCase()
}

/**
 *  删除可能存在的签名，防止重复签名
 */
export function delHashStr(params) {
    if(typeof params === 'object' && !Array.isArray(params) && params !== null && params.hasOwnProperty('sign') && params.hasOwnProperty('convertPOST')){
        delete params.appid;
        delete params.convertPOST;
        delete params.randomstr;
        delete params.sign;
        delete params.timestamp;
    }
    return params
}

/**
 * 是否手机端
 */
export const isMobile = () => {
    return /(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)
}

let headers = { platform:'pc', 'Content-Type': 'application/json;charset=utf-8' };
let $http = {
    get(url,params={}){
        params = delHashStr(params);
        if(!params.sign){
            params.sign = getHashStr(params)
        }
        if(Object.keys(params).length){
            let result = ''
            for(let item in params){
                result = (result?result+'&':'?') + item + '=' + params[item]
            }
            url += result;
        }
        return new Promise(resolve => {
            headers.version = process.env.VERSION;
            headers.token = token;
            headers.Otoken = token;
            headers.timestamp = +new Date();
            if(device) headers.device = device;
            if(lang) headers.lang = lang;
            if(uid) headers.uid = uid;
            if(appid) headers.appid = appid;
            headers.requestid = md5(+new Date() + navigator.userAgent + randomString());
            fetch(url,{
                method:'GET',
                headers:headers,
                body:undefined,
            }).then(xhr => {
                if(xhr.ok){
                    xhr.json().then(res => {
                        resolve(res)
                    })
                }
            }).catch(error => {})
        })
    },
    post(url,params={}){
        params = delHashStr(params);
        if(!params.sign){
            params.sign = getHashStr(params)
        }
        return new Promise(resolve => {
            headers.version = process.env.VERSION;
            headers.token = token;
            headers.Otoken = token;
            headers.timestamp = +new Date();
            if(device) headers.device = device;
            if(lang) headers.lang = lang;
            if(uid) headers.uid = uid;
            if(appid) headers.appid = appid;
            headers.requestid = md5(+new Date() + navigator.userAgent + randomString());
            fetch(url,{
                method:'POST',
                headers:headers,
                body:JSON.stringify(params)
            }).then(xhr => {
                if(xhr.ok){
                    xhr.json().then(res => {
                        resolve(res)
                    })
                }
            })
        })
    }
}
export {lang};
export default $http;
